package com.fitso.wicket.panel.user;

import java.io.Serializable;

import org.apache.log4j.Logger;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.RequiredTextField;
import org.apache.wicket.markup.html.form.StatelessForm;
import org.apache.wicket.model.CompoundPropertyModel;
import org.apache.wicket.validation.validator.EmailAddressValidator;

import com.fitso.wicket.FitsoSession;
import com.fitso.wicket.bean.Credentials;
import com.fitso.wicket.page.landing.Landing;

/**
 * Creates a SignIn form within the SignIn Panel
 * 
 * @author timothystorm
 */
public class UserSignInForm extends StatelessForm<Credentials> implements Serializable {
	// Only change on breaking changes, i.e., removing fields
	private static final long serialVersionUID = 1L;

	private static final Logger logger = Logger.getLogger(UserSignInForm.class);

	public UserSignInForm(final String id) {
		super(id, new CompoundPropertyModel<Credentials>(new Credentials()));

		logger.trace("building signInForm");
		add(new RequiredTextField<String>("email").add(EmailAddressValidator.getInstance()));
		add(new PasswordTextField("password"));
	}

	/**
	 * Handles the submit of the signin panel
	 */
	@Override
	protected void onSubmit() {
		logger.info("user login starting...");

		Credentials credentials = getModelObject();

		if (FitsoSession.get().signIn(credentials.getEmail(), credentials.getPassword())) {
			logger.info("user login successful: " + credentials.getEmail());

			if (!continueToOriginalDestination()) {
				setResponsePage(new Landing());
			}
		} else {
			logger.info("user login failed: " + credentials.getEmail());
			error(getLocalizer().getString("login.Error", this));
		}
	}

	@Override
	protected boolean getStatelessHint() {
		return false;
	}
}